package com.buyi.easyhome.util

import android.content.Context
import android.util.Log
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder
import com.allenliu.versionchecklib.v2.builder.UIData
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener
import org.json.JSONArray
import java.io.Serializable

object VersionCheckerUtil {

    private const val TAG = "VersionChecker"

    // 定义回调接口用于返回结果
    interface VersionCheckCallback : Serializable {
        fun onNeedUpdate(downloadUrl: String)
        fun onNoUpdateNeeded()
        fun onError(errorMsg: String?)
    }

    /**
     * 检查版本更新
     *
     * @param context 上下文
     * @param requestUrl Gitee API 请求地址
     * @param currentVersion 当前应用版本号（如 1.0.0）
     * @param callback 回调处理结果
     */
    fun checkForUpdate(
        context: Context,
        requestUrl: String,
        currentVersion: String,
        callback: VersionCheckCallback
    ) {
        AllenVersionChecker
            .getInstance()
            .requestVersion()
            .setRequestUrl(requestUrl)
            .request(object : RequestVersionListener {
                override fun onRequestVersionSuccess(
                    downloadBuilder: DownloadBuilder?,
                    result: String?
                ): UIData? {
                    Log.d(TAG, "Response: $result")

                    try {
                        val jsonArray = JSONArray(result)
                        if (jsonArray.length() == 0) {
                            Log.e(TAG, "No releases found")
                            callback.onNoUpdateNeeded()
                            return null
                        }

                        val latestRelease = jsonArray.getJSONObject(0)
                        val remoteVersionTag = latestRelease.getString("tag_name") // 如："v1.0.15"

                        // 去除 "v" 前缀，并比较版本
                        val remoteVersion = remoteVersionTag.removePrefix("v")

                        if (isVersionHigher(currentVersion, remoteVersion)) {
                            val downloadUrl = latestRelease.getJSONArray("assets").getJSONObject(0).getString("browser_download_url")
                            callback.onNeedUpdate(downloadUrl)
                            return UIData.create()
                                .setTitle("发现新版本")
                                .setContent("v$currentVersion -> $remoteVersionTag \n是否更新到最新版本？")
                                .setDownloadUrl(downloadUrl)
                        } else {
                            callback.onNoUpdateNeeded()
                            return null
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "解析失败", e)
                        callback.onError(e.message)
                        return null
                    }
                }

                override fun onRequestVersionFailure(message: String?) {
                    Log.e(TAG, "请求失败: $message")
                    callback.onError(message)
                }
            })
            .executeMission(context)
    }

    /**
     * 比较两个版本号大小
     *
     * @param current 当前版本号（如 1.0.0）
     * @param remote 远程版本号（如 1.0.15）
     * @return true 如果远程版本更高
     */
    private fun isVersionHigher(current: String, remote: String): Boolean {
        val currentParts = current.split(".")
        val remoteParts = remote.split(".")

        for (i in 0 until maxOf(currentParts.size, remoteParts.size)) {
            val currentPart = if (i < currentParts.size) currentParts[i].toIntOrNull() ?: 0 else 0
            val remotePart = if (i < remoteParts.size) remoteParts[i].toIntOrNull() ?: 0 else 0

            if (remotePart > currentPart) return true
            if (remotePart < currentPart) return false
        }
        return false
    }
}